<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Redirect;
use Cache;
use Validator;
use DB;
use Log;
use App\Http\Controllers\BaseController;
use App\Http\Lib\Util;
use App\Http\Lib\UserLib;
use App\Entity\UserEntity;

class OAuth2Controller extends BaseController
{
    
    # 登录
    public function login(Request $request)
    {
        if ( \Session::get('uid') )
            return Redirect::to('index');

        return Redirect::to(env('USERCENTER_LOGIN_URL'));
    }

    # 从用户中心注销
    public function uclogout(Request $request)
    {
        $logout_token = $request->logout_token;
        $ip = $request->ip();

        if ( !in_array($ip, explode('|', env('USERCENTER_IPS'))) )
            return $this->e("{$ip} not allowed");

        $session_id = Cache::pull(sprintf('logout_token@%s', $logout_token));
        if ( $session_id == null )
            return $this->e("{$logout_token} invalid");

        \Session::setId($session_id);
        \Session::start();
        \Session::flush();
        \Session::save();
        return $this->o();
    }

    # 从子系统注销
    public function logout(Request $request)
    {
        $logout_token = \Session::get('logout_token', 'xxx');

        $r = $this->privateApi('POST', env('USERCENTER_URL') . '/usercenter/logout', ['logout_token' => $logout_token]);
        if ( !$r || $r['errcode'] !== 0  )
            \Log::info(__METHOD__, $r);

        \Session::flush();
        return Redirect::to(env('USERCENTER_LOGIN_URL'));
    }

    # 从用户中心登录,授权登陆回调
    public function logined(Request $request)
    {
        if ( empty($request->access_token) )
            return $this->errorPage('缺少Token');

        $r = $this->privateApi('POST', env('USERCENTER_URL') . '/api/oauth/info', ['access_token' => $request->access_token]);

        if ( !$r )
            return $this->errorPage('连接用户中心失败(1)');

        if ( !isset($r['errcode']) )
            return $this->errorPage('连接用户中心失败(2)');

        if ( $r['errcode'] != 0 )
            return $this->errorPage($r['errmessage']);


        $uid = $r['data']['user']['id'];
        $name  = $r['data']['user']['name'];
        $email = $r['data']['user']['email'];
        $logout_token = $r['data']['logout_token'];
        Cache::put("userinfo:{$uid}", $r, 1800);

        $user  = User::find($uid);
        if ( $user == null ) {
            $user = new User;
            $user->uc_userid = $uid;
        }

        $user->name = $name;
        $user->email = $email;
        $user->latest_access = time();
        $user->save();
        \Session::put('uid', $uid);
        \Session::put('logout_token', $logout_token);
        Cache::put(sprintf('logout_token@%s', $logout_token), \Session::getId(), 60*24*30);
        return Redirect::to('index');
    }

}
